package com.hy.usercenter.config;

import com.hy.usercenter.filter.LoginFilter;
import com.hy.usercenter.interceptor.LoggingInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description 对请求进行配置。
 *
 * @Author minsf
 * @Date 2023/2/15
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 允许跨域
     * @param registry
     */
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*")
                .allowedHeaders("x-custom-header") // 允许使用的请求头字段
                .allowedHeaders("*");
    }*/

    /**
     * 登录过滤器进行注册
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<LoginFilter> registerLoginFilter() {
        FilterRegistrationBean<LoginFilter> filterRegister =
                new FilterRegistrationBean<>();
        filterRegister.setFilter(new LoginFilter());
        filterRegister.addUrlPatterns("/*");
        filterRegister.setOrder(1);

        //排除登录请求和注册请求
        filterRegister.addInitParameter("exclusions",
                "/api/user/login," +
                        "/api/user/register");

        return filterRegister;
    }


    /**
     * 全局请求日志
     *
     * @param registry 注册器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // registry.addInterceptor(new LoggingInterceptor());

        registry.addInterceptor(new LoggingInterceptor())
                //拦截所有路由
                .addPathPatterns("/**")
                //不拦截路由
                .excludePathPatterns("/api/user/login")
                .excludePathPatterns("/api/user/register")
                .excludePathPatterns("/api/doc.html/**")
                .excludePathPatterns("/api/doc.html#/**")
                .excludePathPatterns("/api/swagger-ui.html")
                //让后台文档不可用可以直接注释掉这两个v2 v3
                .excludePathPatterns("/api/v2/api-docs")    // swagger api json
                .excludePathPatterns("/api/v3/api-docs")
                .excludePathPatterns("/api/swagger-resources/configuration/ui")// 用来获取支持的动作
                .excludePathPatterns("/api/swagger-resources")       // 用来获取api-docs的URI
                .excludePathPatterns("/api/swagger-resources/configuration/security")    // 安全选项
                .excludePathPatterns("/api/swagger-resources/**")
                //补充路径，近期在搭建swagger接口文档时，通过浏览器控制台发现该/webjars路径下的文件被拦截，故加上此过滤条件即可。(2020-10-23)
                .excludePathPatterns("/api/webjars/**")
                .excludePathPatterns("/api/error");


    }
}
